#!/usr/bin/env node

const Koa        = require('koa'),
      bodyparser = require('koa-bodyparser'),
      json       = require('koa-json'),
      jwt        = require('koa-jwt'),
      logger     = require('koa-logger'),
      tasks      = require('./routes/tasks'),
      users      = require('./routes/users'),
      {JWT_KEY}  = require('./lib/constant'),
      jwt2       = require('jsonwebtoken'),
      log        = console.log;

const app        = new Koa();

//ctx 上下文； next 调用后面的中间件

app.use(json());
app.use(logger());
app.use(jwt({secret:JWT_KEY}).unless({path:/\/api\/users\/login$/}));
app.use(bodyparser({ enableTypes:['json','form','text'] }));

app.use(async(ctx,next) => { //parse token get user
  //get token
  let token = ctx.header.authorization;
  if(typeof token !== 'undefined'){
    token = token.split(' ')[1];
    log(`token=${token}`); 
    //parse token get user id
    let user = jwt2.verify(token,JWT_KEY);
    ctx.userId = user.id;
  }
  await next();
});

app.use(tasks.routes());
app.use(users.routes());

app.listen(8080);

